/*
 * @lc app=leetcode.cn id=23 lang=javascript
 *
 * [23] 合并K个升序链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode[]} lists
 * @return {ListNode}
 */
var merge = function (lists, l, r) {
  if (l == r) return lists[l];

  let mid = (l + r) >> 1;
  var left = merge(lists, l, mid);
  var right = merge(lists, mid + 1, r);
  return mergeTwo(left, right);
}
// 合并两个链表
var mergeTwo = function (list1, list2) {
  if (list1 === null || list2 === null) {
    return list1 === null ? list2 : list1;
  }
  // 虚拟头节点
  let head = new ListNode(null);
  // cur: 新链表的尾指针
  let p1 = list1, p2 = list2, cur = head;
  while (p1 !== null && p2 !== null) {
    if (p1.val < p2.val) {
      cur.next = p1;
      p1 = p1.next;
    } else {
      cur.next = p2;
      p2 = p2.next;
    }
    cur = cur.next;
  }
  cur.next = p1 == null ? p2 : p1;
  return head.next;
}
var mergeKLists = function (lists) {
  if (lists.length === 0) return null;
  return merge(lists, 0, lists.length - 1)
};
// @lc code=end

